import { useState, forwardRef, useImperativeHandle } from "react";

import MdEditor from 'for-editor';

import { toolbar } from "../config/markdownConfig";
import { uploadFile } from "../api/modules/file";

const MarkDown = (props:any, ref:any) => {
    const [ mdContent, setMdContent ] = useState('');

    useImperativeHandle(ref, ()=>{
        return {
            mdContent:mdContent
        };
    });
    // 上传图片
    const uploadImg = async (file:File) =>{
        const formData = new FormData();
        formData.append("file", file);
        const { data } = await uploadFile(formData);
        setMdContent(mdContent + `![alt](localhost/file/${data})`);
    };
    // 输入内容改变
    const handleEditorChange = (value:string) =>{
        setMdContent(value);
    };
    // 保存输入内容
    const handleEditorSave = (value:string)=> {
        console.log('handleEditorSave', value);
    };

    return (
        <MdEditor placeholder="请输入Markdown文本" height="400" toolbar={toolbar} value={mdContent} onChange={handleEditorChange} onSave={handleEditorSave} addImg={uploadImg} />
    );
};

export default forwardRef(MarkDown);
